package com.ad.aidai.fragments.my_order.my_send_order;

import android.content.Context;
import android.view.View;
import android.widget.Button;

import com.ad.aidai.R;
import com.ad.aidai.bean.MyOrderBean;
import com.ad.aidai.bean.Order;
import com.ad.aidai.common.ADApp;
import com.ad.aidai.common.RxBus;
import com.ad.aidai.events.CommonEvent;
import com.ad.aidai.fragments.my_order.MyOrderAdapter;
import com.ad.aidai.network.NetWork;
import com.ad.aidai.network.StatusCodeFromNet;
import com.ad.aidai.network.result.GetMyOrderFromNet;
import com.ad.aidai.network.result.NetResult;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * MyReceiveOrderPresenter
 * <p>
 * Created by Yusxon on 17/2/2.
 */

public class MySendOrderPresenter implements MySendOrderContract.Presenter {

    private Context mContext;
    private MySendOrderContract.View mView;
    private CompositeSubscription mSubscriptions;

    private List<MyOrderBean> mOrderData;
    private MyOrderAdapter mAdapter;

    /**
     * 最多显示一次加载多少数据
     */
    private static final int PAGE_SIZE = 10;
    /**
     * 当前加载第几页
     */
    private int currentPage = 1;

    private int clickPosition = -1;

    public MySendOrderPresenter(Context context, MySendOrderContract.View view) {
        this.mContext = context;
        this.mView = view;
        mView.setPresenter(this);
        mOrderData = new ArrayList<>();
    }

    @Override
    public List<MyOrderBean> getOrderData() {
        return mOrderData;
    }

    @Override
    public void loadMoreOrders() {
        NetWork.getAccountOperationApi()
                .getMySendOrder(ADApp.getUser().getUserId(), PAGE_SIZE, currentPage)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<GetMyOrderFromNet>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        MobclickAgent.reportError(mContext, e);
                        Logger.t("MySendOrderPresenter").e(e.getMessage());
                        mView.toast("加载失败");
                        mAdapter.stopMore();
                    }

                    @Override
                    public void onNext(GetMyOrderFromNet result) {
                        Logger.t("MySendOrderPresenter").i("loadMoreOrders:" + result.toString());
                        if (result.getCode() == StatusCodeFromNet.CODE_SUCCESS) {
                            List<Order> orders = result.getData();
                            Logger.t("MySendOrderPresenter").i(orders.size() + "--");
                            currentPage++;
                            List<MyOrderBean> myOrderBeen = new ArrayList<>();
                            for (Order order : orders) {
                                MyOrderBean bean = new MyOrderBean();
                                bean.setValue(order);
                                bean.setUIType(MyOrderBean.UITYPE_SEND);
                                switch (order.getOrderStatus()) {
                                    case Order.STATUS_CANCEL:
                                        bean.setType(MyOrderBean.VIEWTYPE_TOP);
                                        break;
                                    case Order.STATUS_NO_RECIEVE:
                                    case Order.STATUS_NO_ACCEPTANCE:
                                    case Order.STATUS_SENDER_NO_SCORE:
                                    case Order.STATUS_NO_SCORE:
                                        bean.setType(MyOrderBean.VIEWTYPE_COMMON);
                                        break;
                                    case Order.STATUS_RECIEVER_STATE:
                                    case Order.STATUS_STATE:
                                        if (order.getSenderComment() == null) {
                                            bean.setType(MyOrderBean.VIEWTYPE_TOP);
                                        }
                                        break;
                                    default:
                                        bean.setType(MyOrderBean.VIEWTYPE_COMPLETE);
                                        break;
                                }
                                myOrderBeen.add(myOrderBeen.size(), bean);
                            }
                            mAdapter.addAll(myOrderBeen);
                            if (orders.size() == 0) {
                                //暂停加载,暂时改为,停止下载则底部变成没有更多了且不可以点击
                                mAdapter.pauseMore();
                            } else {
                                //停止加载,底部变为点击加载更多
                                mAdapter.stopMore();
                            }
                        } else {
                            mView.toast("加载失败");
                            Logger.t("MySendOrderPresenter").e(result.toString());
                            //停止加载,底部变为点击加载更多
                            mAdapter.stopMore();
                        }
                    }
                });
    }

    @Override
    public void refresh() {
        mView.setOnRefresh(true);
        NetWork.getAccountOperationApi()
                .getMySendOrder(ADApp.getUser().getUserId(), PAGE_SIZE, 1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<GetMyOrderFromNet>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        MobclickAgent.reportError(mContext, e);
                        Logger.t("OrderAllSchoolPresenter").e(e.getMessage());
                        mView.toast("刷新失败");
                        mView.setOnRefresh(false);
                        mAdapter.add(null);
                    }

                    @Override
                    public void onNext(GetMyOrderFromNet result) {
                        Logger.t("OrderAllSchoolPresenter").i("refreshOrders:" + result.toString());
                        mView.setOnRefresh(false);
                        if (result.getCode() == StatusCodeFromNet.CODE_SUCCESS) {
                            List<Order> orders = result.getData();
                            Logger.t("OrderAllSchoolPresenter").i(orders.size() + "--");
                            currentPage = 2;
                            mAdapter.clear();
                            List<MyOrderBean> myOrderBeen = new ArrayList<>();
                            for (Order order : orders) {
                                MyOrderBean bean = new MyOrderBean();
                                bean.setValue(order);
                                bean.setUIType(MyOrderBean.UITYPE_SEND);
                                switch (order.getOrderStatus()) {
                                    case Order.STATUS_CANCEL:
                                        bean.setType(MyOrderBean.VIEWTYPE_TOP);
                                        break;
                                    case Order.STATUS_NO_RECIEVE:
                                    case Order.STATUS_NO_ACCEPTANCE:
                                    case Order.STATUS_SENDER_NO_SCORE:
                                    case Order.STATUS_NO_SCORE:
                                        bean.setType(MyOrderBean.VIEWTYPE_COMMON);
                                        break;
                                    case Order.STATUS_RECIEVER_STATE:
                                    case Order.STATUS_STATE:
                                        if (order.getSenderComment() == null) {
                                            bean.setType(MyOrderBean.VIEWTYPE_TOP);
                                        }
                                        break;
                                    default:
                                        bean.setType(MyOrderBean.VIEWTYPE_COMPLETE);
                                        break;
                                }
                                myOrderBeen.add(myOrderBeen.size(), bean);
                            }
                            mAdapter.addAll(myOrderBeen);
                            mAdapter.stopMore();
                        } else {
                            mView.toast("刷新失败");
                            mAdapter.add(null);
                            Logger.t("OrderAllSchoolPresenter").e(result.toString());
                        }
                    }
                });
    }

    @Override
    public void subscribe() {
        mSubscriptions = new CompositeSubscription();
    }

    @Override
    public void unSubscribe() {
        mContext = null;
        mView = null;
        mSubscriptions.clear();
        mSubscriptions = null;
    }

    @Override
    public void setAdapter() {
        this.mAdapter = mView.getAdapter();
    }

    @Override
    public void onItemSubClick(View view, int position) {
        switch (view.getId()) {
            case R.id.btn_my_order_button:
                Button btn = (Button) view;
                clickPosition = position;

                switch (btn.getText().toString()) {
                    case "撤销":
                        mView.showDialog("是否撤销该订单?", "撤销");
                        break;
                    case "完成":
                        mView.showDialog("对方是否已完成该订单?", "完成");
                        break;
                    case "评分":
                        ADApp.setOrder(mAdapter.getItem(clickPosition).getValue());
                        mView.gotoComment();
                        break;
                    default:
                        break;
                }
                break;
        }
    }

    @Override
    public void onItemClick(int position) {
        ADApp.setOrder(mAdapter.getItem(position).getValue());
    }

    @Override
    public void clickDialogSure(String btnText) {
        switch (btnText) {
            case "撤销":
                withdrawOrder();
                break;
            case "完成":
                finishOrder();
                break;
            default:
                break;
        }
    }

    /**
     * 撤单
     */
    private void withdrawOrder() {
        mView.showLoading("撤单");
        NetWork.getOrderOperationApi()
                .withdrawOrder(mAdapter.getItem(clickPosition).getValue().getOrderId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NetResult>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        MobclickAgent.reportError(mContext, e);
                        Logger.t("OrderDetailPresenter").e(e.getMessage());
                        mView.closeLoading(false);
                    }

                    @Override
                    public void onNext(NetResult result) {
                        if (result.getCode() == StatusCodeFromNet.CODE_SUCCESS) {
                            mView.closeLoading(true);
                            try {
                                mAdapter.getItem(clickPosition).setType(MyOrderBean.VIEWTYPE_TOP);
                                mAdapter.getItem(clickPosition).getValue().setOrderStatus(Order.STATUS_CANCEL);
                                Order order = mAdapter.getItem(clickPosition).getValue();
                                RxBus.getInstance().postEvent(new CommonEvent<>(CommonEvent.ORDER_STATUS_CHANGE,
                                        order));
                                mAdapter.notifyItemChanged(clickPosition);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            Logger.t("OrderDetailPresenter").e(result.toString());
                            //停止加载,底部变为点击加载更多
                            mView.closeLoading(false);
                        }
                    }
                });
    }

    /**
     * 完成单
     */
    private void finishOrder() {
        mView.showLoading("提交");
        NetWork.getOrderOperationApi()
                .finishOrder(mAdapter.getItem(clickPosition).getValue().getOrderId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NetResult>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        MobclickAgent.reportError(mContext, e);
                        Logger.t("OrderDetailPresenter").e(e.getMessage());
                        mView.closeLoading(false);
                    }

                    @Override
                    public void onNext(NetResult result) {
                        if (result.getCode() == StatusCodeFromNet.CODE_SUCCESS) {
                            mView.closeLoading(true);
                            mAdapter.getItem(clickPosition).getValue().setOrderStatus(Order.STATUS_COMPLETE);
                            Order order = mAdapter.getItem(clickPosition).getValue();
                            RxBus.getInstance().postEvent(new CommonEvent<>(CommonEvent.ORDER_STATUS_CHANGE,
                                    order));
                            mAdapter.notifyItemChanged(clickPosition);
                        } else {
                            Logger.t("OrderDetailPresenter").e(result.toString());
                            //停止加载,底部变为点击加载更多
                            mView.closeLoading(false);
                        }
                    }
                });
    }

    @Override
    public void orderStatusChange(Order order) {
        if (mAdapter != null && mAdapter.getCount() > 0) {
            int position = 0;
            for (MyOrderBean orderBean : mAdapter.getAllData()) {
                Order oldOrder = orderBean.getValue();
                if (oldOrder.getOrderId() == order.getOrderId()) {
                    if (order.getOrderStatus() != Order.STATUS_COMPLETE && order.getOrderStatus() != Order
                            .STATUS_CANCEL) {
                        orderBean.setValue(order);
                        switch (order.getOrderStatus()) {
                            case Order.STATUS_NO_RECIEVE:
                            case Order.STATUS_NO_ACCEPTANCE:
                            case Order.STATUS_SENDER_NO_SCORE:
                            case Order.STATUS_NO_SCORE:
                                orderBean.setType(MyOrderBean.VIEWTYPE_COMMON);
                                break;
                            case Order.STATUS_RECIEVER_STATE:
                            case Order.STATUS_STATE:
                                if (order.getSenderComment() == null) {
                                    orderBean.setType(MyOrderBean.VIEWTYPE_TOP);
                                }
                                break;
                            default:
                                orderBean.setType(MyOrderBean.VIEWTYPE_COMPLETE);
                                break;
                        }
                        mAdapter.notifyItemChanged(position);
                    }
                    break;
                }
                position++;
            }
        }
    }
}
